/**
 * Copyright &copy; 2012-2014 <a href="https://github.cn.apestar">JeeSite</a> All rights reserved.
 */
package cn.apestar.modules.sys.web;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.http.client.ClientProtocolException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import redis.clients.jedis.Jedis;
import cn.apestar.common.beanvalidator.BeanValidators;
import cn.apestar.common.config.Global;
import cn.apestar.common.persistence.BaseEntity;
import cn.apestar.common.persistence.Page;
import cn.apestar.common.utils.CookieUtils;
import cn.apestar.common.utils.DateUtils;
import cn.apestar.common.utils.JedisUtils;
import cn.apestar.common.utils.StringUtils;
import cn.apestar.common.utils.excel.ExportExcel;
import cn.apestar.common.utils.excel.ImportExcel;
import cn.apestar.common.web.BaseController;
import cn.apestar.core.http.AppType;
import cn.apestar.modules.cache.RemoveCacheUtil;
import cn.apestar.modules.sys.entity.User;
import cn.apestar.modules.sys.entity.UserAndInstituion;
import cn.apestar.modules.sys.entity.UserFilter;
import cn.apestar.modules.sys.entity.WtUser;
import cn.apestar.modules.sys.service.SystemService;
import cn.apestar.modules.sys.service.UserAndInstituionService;
import cn.apestar.modules.sys.service.UserService;
import cn.apestar.modules.sys.utils.UserUtils;
import cn.apestar.user.api.enums.UserType;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 用户Controller
 * @author ThinkGem
 * @version 2013-8-29
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/userTs")
public class UserTsController extends BaseController {

    @Autowired
    private SystemService systemService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserAndInstituionService userAndInstituionService;

    @ModelAttribute
    public WtUser get(@RequestParam(required = false) String id) {

        if (StringUtils.isNotBlank(id)) {
            return userService.get(id);
        } else {
            return new WtUser();
        }
    }

    @RequestMapping(value = {"index"})
    public String index(User user, Model model) {

        return "modules/sys/user/userIndex";
    }

    @RequestMapping(value = {"list" , ""})
    public String list(User user, HttpServletRequest request, HttpServletResponse response, Model model) {

        Page<User> page = systemService.findUser(new Page<User>(request, response), user);
        model.addAttribute("page", page);
        return "modules/sys/user/userList";
    }

    /**
     * 会员查询
     * @param user
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = {"listHY"})
    public String listHY(UserFilter user, HttpServletRequest request, HttpServletResponse response, Model model) {

        user.setUserType(UserType.PARENT.getValue());
        user.setDelFlag(BaseEntity.DEL_FLAG_NORMAL);
        Page<WtUser> page = userService.findUserList(new Page<WtUser>(request, response), user);
        model.addAttribute("page", page);
        model.addAttribute("user", user);
        return "modules/sys/hy/userListhy";
    }

    /**
     * 会员查询 - 回收站
     * @param user
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = {"listHSZ"})
    public String listHSZ(UserFilter user, HttpServletRequest request, HttpServletResponse response, Model model) {

        user.setUserType(UserType.PARENT.getValue());
        user.setDelFlag(BaseEntity.DEL_FLAG_DELETE);
        Page<WtUser> page = userService.findUserList(new Page<WtUser>(request, response), user);
        model.addAttribute("page", page);
        model.addAttribute("user", user);
        return "modules/sys/hy/userListhy";
    }

    /**
     * 会员对象编辑修改
     * @param user
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = "formHY")
    public String formHY(@RequestParam(required = false) String id, Model model) {

        WtUser user = userService.get(id);
        if (user == null) {
            user = new WtUser();
        }
        user.setUserType(UserType.PARENT.getValue());
        model.addAttribute("user", user);
        return "modules/sys/hy/userFormhy";
    }

    /**
     * 会员对象明细查询
     * @param user
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = "formHYDetail")
    public String formHYDetail(WtUser user, Model model) {

        model.addAttribute("user", user);
        model.addAttribute("allRoles", systemService.findAllRole());
        return "modules/sys/hy/userFormhyDetail";
    }

    /**
     * 老师查询
     * @param user
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = {"listJJR"})
    public String listJJR(UserFilter user, HttpServletRequest request, HttpServletResponse response, Model model) {

        user.setApp(AppType.NTO.getValue());
        user.setDelFlag(BaseEntity.DEL_FLAG_NORMAL);
        Page<WtUser> page = userService.findUserList(new Page<WtUser>(request, response), user);
        model.addAttribute("page", page);
        model.addAttribute("user", user);
        return "modules/sys/hy/userListjjr";
    }

    /**
     * 老师查询 -search
     * @param user
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = {"listJJRSelect"})
    public String listJJRSelect(UserFilter user, HttpServletRequest request, HttpServletResponse response, Model model) {

        user.setApp(AppType.NTO.getValue());
        user.setDelFlag(BaseEntity.DEL_FLAG_NORMAL);
        Page<WtUser> page = userService.findUserList(new Page<WtUser>(request, response), user);
        model.addAttribute("page", page);
        model.addAttribute("user", user);
        return "modules/sys/hy/userListjjrSelected";
    }

    /**
     * 老师查询-回收站
     * @param user
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = {"listJJRSHZ"})
    public String listJJRSHZ(UserFilter user, HttpServletRequest request, HttpServletResponse response, Model model) {

        user.setApp(AppType.NTO.getValue());
        user.setDelFlag(BaseEntity.DEL_FLAG_DELETE);
        Page<WtUser> page = userService.findUserList(new Page<WtUser>(request, response), user);
        model.addAttribute("page", page);
        model.addAttribute("user", user);
        return "modules/sys/hy/userListjjr";
    }

    /**
     * 老师对象编辑修改
     * @param user
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = "formJJR")
    public String formJJR(WtUser user, Model model) {

        if (user == null) {
            user = new WtUser();
        }
        user.setApp(AppType.NTO.getValue());
        user.setUserType(UserType.EMPLOYEE.getValue());
        UserAndInstituion userAndInstituion = new UserAndInstituion();
        userAndInstituion.setUserId(user.getId());
        if (user.getId() != null)
            user.setUserAndInstituionList(userAndInstituionService.findList(userAndInstituion));
        model.addAttribute("user", user);
        return "modules/sys/hy/userFormJJR";
    }

    /**
     * 老师对象查询
     * @param user
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = "formJJRDetail")
    public String formJJRDetail(WtUser user, Model model) {

        model.addAttribute("user", user);
        return "modules/sys/hy/userFormjjrDetail";
    }

    @RequestMapping(value = "save")
    public String save(WtUser user, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {

        // 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
        // 如果新密码为空，则不更换密码
        if (StringUtils.isNotBlank(user.getNewPassword())) {
            user.setPassword(user.getNewPassword());
        } else
            user.setPassword(null);
        // // 保存用户信息
        boolean b = checkLoginNameUser(null, user.getPhone(), user.getApp(), user.getId());
        try {
            if (b) {
                addMessage(redirectAttributes, "保存用户'" + user.getAccount() + "'成功");
                user.setUserType(UserType.EMPLOYEE.getValue());
                user.setApp(AppType.NTO.getValue());
                userService.saveUser(user);
            }
        } catch (Exception e) {
            addMessage(redirectAttributes, "登录名重复！");
            e.printStackTrace();
        }

        if (b) {
            if (UserType.PARENT.getValue().equals(user.getUserType())) {
                return "redirect:" + adminPath + "/sys/user/listHY";
            }
            if (AppType.NTO.getValue().equals(user.getApp())) {
                return "redirect:" + adminPath + "/sys/user/listJJR";
            }
        } else {

            if (UserType.PARENT.getValue().equals(user.getUserType())) {
                return "redirect:" + adminPath + "/sys/user/listHY";
            }
            if (AppType.NTO.getValue().equals(user.getUserType())) {
                return "redirect:" + adminPath + "/sys/user/listJJR";
            }
        }
        return "redirect:" + adminPath + "/sys/user/list?repage";
    }

    @RequestMapping(value = "delete")
    public String delete(WtUser user, RedirectAttributes redirectAttributes) {

        userService.delete(user);
        addMessage(redirectAttributes, "删除用户成功");
        if (UserType.PARENT.getValue().equals(user.getUserType())) {
            return "redirect:" + adminPath + "/sys/user/listHY?repage";
        }
        if (AppType.NTO.getValue().equals(user.getUserType())) {
            return "redirect:" + adminPath + "/sys/user/listJJR?repage";
        }
        return "redirect:" + adminPath + "/sys/user/list?repage";
    }

    @RequestMapping(value = "updateUser")
    public String updateUser(WtUser user, RedirectAttributes redirectAttributes) {

        userService.updateUser(user);
        addMessage(redirectAttributes, "还原用户成功");
        if (UserType.PARENT.getValue().equals(user.getUserType())) {
            return "redirect:" + adminPath + "/sys/user/listHSZ?repage";
        }
        if (AppType.NTO.getValue().equals(user.getUserType())) {
            return "redirect:" + adminPath + "/sys/user/listJJRSHZ?repage";
        }
        return "redirect:" + adminPath + "/sys/user/list?repage";
    }

    /**
     * 导出用户数据
     * @param user
     * @param request
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("sys:user:view")
    @RequestMapping(value = "export", method = RequestMethod.POST)
    public String exportFile(User user, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {

        try {
            String fileName = "用户数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            Page<User> page = systemService.findUser(new Page<User>(request, response, -1), user);
            new ExportExcel("用户数据", User.class).setDataList(page.getList()).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出用户失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + adminPath + "/sys/user/list?repage";
    }

    /**
     * 导入用户数据
     * @param file
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {

        if (Global.isDemoMode()) {
            addMessage(redirectAttributes, "演示模式，不允许操作！");
            return "redirect:" + adminPath + "/sys/user/list?repage";
        }
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<User> list = ei.getDataList(User.class);
            for (User user : list) {
                try {
                    if ("true".equals(checkLoginName("", user.getLoginName()))) {
                        user.setPassword(SystemService.entryptPassword("123456"));
                        BeanValidators.validateWithException(validator, user);
                        systemService.saveUser(user, false);
                        successNum++;
                    } else {
                        failureMsg.append("<br/>登录名 " + user.getLoginName() + " 已存在; ");
                        failureNum++;
                    }
                } catch (ConstraintViolationException ex) {
                    failureMsg.append("<br/>登录名 " + user.getLoginName() + " 导入失败：");
                    List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
                    for (String message : messageList) {
                        failureMsg.append(message + "; ");
                        failureNum++;
                    }
                } catch (Exception ex) {
                    failureMsg.append("<br/>登录名 " + user.getLoginName() + " 导入失败：" + ex.getMessage());
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条用户，导入信息如下：");
            }
            addMessage(redirectAttributes, "已成功导入 " + successNum + " 条用户" + failureMsg);
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入用户失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + adminPath + "/sys/user/list?repage";
    }

    /**
     * 下载导入用户数据模板
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("sys:user:view")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {

        try {
            String fileName = "用户数据导入模板.xlsx";
            List<User> list = Lists.newArrayList();
            list.add(UserUtils.getUser());
            new ExportExcel("用户数据", User.class, 2).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + adminPath + "/sys/user/list?repage";
    }

    /**
     * 验证登录名是否有效
     * @param oldLoginName
     * @param loginName
     * @return
     */
    @ResponseBody
    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "checkLoginName")
    public String checkLoginName(String oldLoginName, String loginName) {

        if (loginName != null && loginName.equals(oldLoginName)) {
            return "true";
        } else if (loginName != null && systemService.getUserByLoginName(loginName, null) == null) {
            return "true";
        }
        return "false";
    }

    /**
     * 验证登录名是否有效
     * @param oldLoginName
     * @param loginName
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "checkLoginNameUser")
    public boolean checkLoginNameUser(String oldLoginName, @RequestParam("account") String loginName, String app, String id) {

        if (loginName != null && loginName.equals(oldLoginName)) {
            return true;
        } else if (loginName != null && userService.getUserByLoginName(loginName, app, id) == null) {
            return true;
        }
        return false;
    }

    /**
     * 推出登录
     */
    @RequestMapping(value = "logoutWeb")
    public String logoutWeb(HttpServletRequest request, HttpServletResponse response, Model model) {

        String redirectUri = request.getParameter("uri");
        CookieUtils.setCookie(response, "LOGINED", "false");
        if (UserUtils.getSubject() != null)
            UserUtils.getSubject().logout();
        if (redirectUri == null || redirectUri.isEmpty()) {
            return "redirect:" + adminPath + "/login";
        } else {
            Jedis jedis = null;
            try {
                jedis = JedisUtils.getResource();
                jedis.del(JedisUtils.getBytesKey("shiro_session_" + request.getSession().getId()));
            } catch (Exception e) {
                logger.error("update {} {}", request.getSession().getId(), request != null ? request.getRequestURI() : "", e);
            } finally {
                JedisUtils.returnResource(jedis);
            }
            return "redirect:" + adminPath + redirectUri;
        }
    }

    /**
     * 用户信息显示及保存
     * @param user
     * @param model
     * @return
     */
    @RequestMapping(value = "info")
    public String info(User user, HttpServletResponse response, Model model) {

        User currentUser = UserUtils.getUser();
        if (StringUtils.isNotBlank(user.getName())) {
            if (Global.isDemoMode()) {
                model.addAttribute("message", "演示模式，不允许操作！");
                return "modules/sys/user/userInfo";
            }
            currentUser.setEmail(user.getEmail());
            currentUser.setPhone(user.getPhone());
            currentUser.setRemarks(user.getRemarks());
            currentUser.setPhoto(user.getPhoto());
            systemService.updateUserInfo(currentUser);
            model.addAttribute("message", "保存用户信息成功");
        }
        model.addAttribute("user", currentUser);
        model.addAttribute("Global", new Global());
        return "modules/sys/user/userInfo";
    }

    /**
     * 返回用户信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "infoData")
    public User infoData() {

        return UserUtils.getUser();
    }

    /**
     * 修改个人用户密码
     * @param oldPassword
     * @param newPassword
     * @param model
     * @return
     */
    @RequestMapping(value = "modifyPwd")
    public String modifyPwd(String oldPassword, String newPassword, Model model) {

        User user = UserUtils.getUser();
        if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)) {
            if (Global.isDemoMode()) {
                model.addAttribute("message", "演示模式，不允许操作！");
                return "modules/sys/user/userModifyPwd";
            }
            if (SystemService.validatePassword(oldPassword, user.getPassword())) {
                systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
                model.addAttribute("message", "修改密码成功");
            } else {
                model.addAttribute("message", "修改密码失败，旧密码错误");
            }
        }
        model.addAttribute("user", user);
        return "modules/sys/user/userModifyPwd";
    }

    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> treeData(@RequestParam(required = false) String officeId, HttpServletResponse response) {

        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<User> list = systemService.findUserByOfficeId(officeId);
        for (int i = 0; i < list.size(); i++) {
            User e = list.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", "u_" + e.getId());
            map.put("pId", officeId);
            map.put("name", StringUtils.replace(e.getName(), " ", ""));
            mapList.add(map);
        }
        return mapList;
    }

    @ResponseBody
    @RequestMapping(value = "clearCache/id/{userId}")
    public Object clearCache(@PathVariable("userId") String userId) throws ClientProtocolException, IOException {

        WtUser user = userService.get(userId);
        if (user != null) {
            RemoveCacheUtil.removeUserCache(userId);
        }
        return getDefaultSuccessMessage();
    }

    /**
     * 注册IM
     * @author lvh 2016年3月24日 下午1:32:20</br>
     * @param userId
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     * @return Object
     */
    @ResponseBody
    @RequestMapping(value = "regIm/id/{userId}")
    public Object regIm(@PathVariable("userId") String userId) throws ClientProtocolException, IOException {

        WtUser user = userService.get(userId);
        userService.initChat(user);
        return getDefaultSuccessMessage();
    }

    /**
     * MB用户名
     * @param user
     * @param request
     * @param response
     * @param model
     * @return /meibang-admin/src/main/webapp/WEB-INF/views/modules/sys/hy/userListMb.jsp
     */
    @RequestMapping(value = {"listMB"})
    public String listMB(UserFilter user, HttpServletRequest request, HttpServletResponse response, Model model) {

        user.setDelFlag("1");
        Page<WtUser> page = userService.findUserList(new Page<WtUser>(request, response), user);
        model.addAttribute("page", page);
        model.addAttribute("user", user);
        return "modules/sys/hy/userListMb";
    }
}
